//
//  DrawImageView.m
//  Paoli
//
//  Created by zlb on 15/11/16.
//  Copyright © 2015年 Ins24.com. All rights reserved.
//

#import "DrawImageView.h"

@interface DrawImageView ()
@property (nonatomic ,strong) UIBezierPath *path;
@property (nonatomic ,strong) NSMutableArray *pathArr;
@end

@implementation DrawImageView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        
    }
    return self;
}
-(void)drawRect:(CGRect)rect
{
    for (id obj in self.pathArr) {
        if ([obj isKindOfClass:[UIImage class]]) {
            [self.image drawInRect:self.bounds];
        }else
        {
            [[UIColor redColor]set];
            [self.path stroke];
        }
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint startP = [touch locationInView:touch.view];
    [self.path moveToPoint:startP];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint movedP = [touch locationInView:touch.view];
    [self.path addLineToPoint:movedP];
    
    
    [self setNeedsDisplay];
}

- (CGRect)caculatorImageFrame
{
    if (self.image) {
        CGFloat imageH = self.image.size.height * SCREEN_WIDTH/self.image.size.width;
        CGFloat x = 0;
        CGFloat y = (SCREEN_HEIGHT - imageH) / 2;
        return CGRectMake(x, y, SCREEN_WIDTH, imageH);
    }
    return CGRectZero;
}

- (UIImage *)saveImage
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [self.layer renderInContext:ctx];
    UIImage * getImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  getImage;
}


- (void)setImage:(UIImage *)image
{
    _image = image;
    [self.pathArr addObject:image];
}
-(NSMutableArray *)pathArr
{
    if (!_pathArr) {
        _pathArr = [NSMutableArray array];
    }
    return _pathArr;
}
- (UIBezierPath *)path
{
    if (!_path) {
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        path.lineWidth = 2;
        path.lineCapStyle = kCGLineCapRound;
        self.path = path;
        [self.pathArr addObject:path];
    }
    
    return _path;
}

@end
